package com.it135.citytraffic.task;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.it135.citytraffic.pojo.entity.Crossing;
import com.it135.citytraffic.pojo.entity.RoadStatistic;
import com.it135.citytraffic.pojo.entity.RoadTimeStatistic;
import com.it135.citytraffic.pojo.entity.TrafficInfo;
import com.it135.citytraffic.service.ICrossingService;
import com.it135.citytraffic.service.IRoadStatisticService;
import com.it135.citytraffic.service.IRoadTimeStatisticService;
import com.it135.citytraffic.service.ITrafficInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时统计数据
 */
@Component
@Slf4j
public class staticTask {


    @Autowired
    private ICrossingService crossingService;
    @Autowired
    private ITrafficInfoService trafficInfoService;
    @Autowired
    private IRoadStatisticService roadStatisticService;

    @Autowired
    private IRoadTimeStatisticService roadTimeStatisticService;


    /**
     * 抽离数据
     */
    @Scheduled(cron = "0 0 0  * * ?")
    void pullData() {
        List<Crossing> crossingListlist = crossingService.list();
//        设置启止时间
        LocalDateTime endTime =LocalDateTime.now();
        LocalDateTime beginTime = endTime.plusDays(-1);
        log.info("统计开始,开始时间：{}，结束时间：{}",beginTime,endTime);
//       遍历路口
        for (Crossing crossing : crossingListlist) {
//根据crossingId获取描述
            List<TrafficInfo> descriptionList = trafficInfoService.list(new LambdaQueryWrapper<TrafficInfo>()
                    .eq(TrafficInfo::getCrossingId, crossing.getId())
                    .select(TrafficInfo::getCreateTime, TrafficInfo::getDescription, TrafficInfo::getCrossingId)
                    .gt(TrafficInfo::getCreateTime, beginTime)
                    .lt(TrafficInfo::getCreateTime, endTime)
            );
//对路况里面的数据进行抽离
            for (TrafficInfo trafficInfo : descriptionList) {
                LocalDateTime occurrenceTime = trafficInfo.getCreateTime();
                String description = trafficInfo.getDescription();
                String[] roadInfoList = description.substring(0, description.length() - 1).split("；");
                if (roadInfoList.length != 0) {
                    for (String roadInfo : roadInfoList) {
                        String[] road = roadInfo.split("：");
                        String roadName = road[0];
                        int roadStatus = 0;
                        String[] directionList = road[1].split("，");
//                            遍历方向.保存
                        for (int i = 0; i < directionList.length; i++) {
                            String direction = directionList[i];
                            if (direction.contains("缓慢")) {
                                roadStatus = 2;
                            } else if (direction.contains("严重拥堵")) {
                                roadStatus = 4;
                            } else if (direction.contains("拥堵")) {
                                roadStatus = 3;
                            } else if (direction.contains("畅通")) {
                                roadStatus = 1;
                            }
                            if (direction.contains("反向")) {
                                direction = turningDirection(directionList[i - 1]);
                            }
                            if (direction.contains("行驶") || direction.contains("严重")) {
                                direction = direction.substring(0, direction.length() - 2);
                            }
                            direction = direction.substring(0, direction.length() - 2);
                            saveRoadStatic(occurrenceTime, new RoadStatistic(null, Math.toIntExact(crossing.getId()), roadName, direction, roadStatus));
                        }
                    }
                }
            }
        }
    }

    /**
     * 反转方向
     * @param s
     * @return
     */
    private String turningDirection(String s) {

//        处理  从龙舟路到锦东路行驶缓慢 双桥子立交桥附近自东向西行驶缓慢
        if (s.contains("到")) {
            String[] split = s.split("到");
            String firstRoad = split[0].substring(1);
            String lsatRoad = split[1].substring(0, split[1].length() - 4);
            return "从" + lsatRoad + "到" + firstRoad + "xx";
        }
        if (s.contains("附近")) {
            String[] split = s.split("附近");
            return split[0] + "附近" + turningDirection(split[1]);
        }
//        处理只有方向名次的情况
        if (s.contains("自北向南")) {
            return "自南向北xx";
        } else if (s.contains("自南向北")) {
            return "自北向南xx";
        } else if (s.contains("自西向东")) {
            return "自东向西xx";
        } else if (s.contains("自东向西")) {
            return "自西向东xx";
        }
        return "未知";
    }
    /**
     * 保存统计数据
     * @param occurrenceTime
     * @param roadStatistic
     */
    private void saveRoadStatic(LocalDateTime occurrenceTime, RoadStatistic roadStatistic) {
//        获取时间段
        int begin = occurrenceTime.getHour();
        int end = occurrenceTime.plusHours(1).getHour();
        String period = begin + "," + end;
        LocalDateTime now = LocalDateTime.now();
//查询之前是否有
        List<RoadStatistic> list = roadStatisticService.list(new LambdaUpdateWrapper<RoadStatistic>()
                .eq(RoadStatistic::getName, roadStatistic.getName())
                .eq(RoadStatistic::getCrossingId, roadStatistic.getCrossingId())
                .eq(RoadStatistic::getDirection, roadStatistic.getDirection())
                .eq(RoadStatistic::getStatus, roadStatistic.getStatus()));
        if (list == null || list.size() == 0) {
            //            不存在则插入
            roadStatisticService.save(roadStatistic);
            roadTimeStatisticService.save(new RoadTimeStatistic(null, roadStatistic.getId(), period, 1, now, now));
        } else {
            Long RoadStatisticId = list.get(0).getId();
            List<RoadTimeStatistic> roadTimeStatistics = roadTimeStatisticService.list(new LambdaQueryWrapper<RoadTimeStatistic>()
                    .eq(RoadTimeStatistic::getRoadStatisticId, RoadStatisticId)
                    .eq(RoadTimeStatistic::getTime, period));
            if (roadTimeStatistics == null || roadTimeStatistics.size() == 0) {
                roadTimeStatisticService.save(new RoadTimeStatistic(null, RoadStatisticId, period, 1, now, now));
            } else {
//                存在数量加1
                roadTimeStatisticService.update(new LambdaUpdateWrapper<RoadTimeStatistic>()
                        .eq(RoadTimeStatistic::getRoadStatisticId, RoadStatisticId)
                        .eq(RoadTimeStatistic::getTime, period)
                        .setSql("count = count + 1 ")
                        .setSql("update_time = now()")
                );
            }
        }
    }
}
